import { Rectangle } from "pixi.js";
import { Sprite } from "@/sprites/Sprite.js";
import { TouchInput } from "@/core/TouchInput.js";

export class Sprite_Button extends Sprite {
    constructor(source) {
        super(source);
        this._touching = false;
        this._coldFrame = null;
        this._hotFrame = null;
        this._clickHandler = null;
    }

    update() {
        super.update();
        this.updateFrame();
        this.processTouch();
    }

    updateFrame() {
        let frame=null;
        if (this._touching) {
            frame = this._hotFrame;
        } else {
            frame = this._coldFrame;
        }
        if (frame) {
            this.setFrame(frame.x, frame.y, frame.width, frame.height);
        }
    }

    setColdFrame(x, y, width, height) {
        if(this._coldFrame){
            this._coldFrame.set(x, y, width, height);
        }else{
            this._coldFrame = new Rectangle(x, y, width, height);
        }
    }

    setHotFrame(x, y, width, height) {
        if(this._coldFrame){
             this._hotFrame.set(x, y, width, height);
        }else{
             this._hotFrame = new Rectangle(x, y, width, height);
        }
    }

    setClickHandler(method) {
        this._clickHandler = method;
    }

    callClickHandler() {
        if (this._clickHandler) {
            this._clickHandler();
        }
    }

    processTouch() {
        if (this.isActive()) {
            if (TouchInput.isTriggered() && this.isButtonTouched()) {
                this._touching = true;
            }
            if (this._touching) {
                if (TouchInput.isReleased() || !this.isButtonTouched()) {
                    this._touching = false;
                    if (TouchInput.isReleased()) {
                        this.callClickHandler();
                    }
                }
            }
        } else {
            this._touching = false;
        }
    }

    isActive() {
        let node = this;
        while (node) {
            if (!node.visible) {
                return false;
            }
            node = node.parent;
        }
        return true;
    }

    isButtonTouched() {
        let {x,y} = this.toLocal({x:TouchInput.x,y:TouchInput.y});
        return x >= 0 && y >= 0 && x < this.width && y < this.height;
    }
}